<template>
  <div class="login">
    <!-- 关闭图标 -->
    <span class="close-btn" @click="$router.back()">
      <i class="iconicon-test iconfont"></i
    ></span>
    <span class="logo">
      <!-- Logo -->
      <i class="iconnew iconfont"></i>
    </span>
    <MyInput
      v-model="user.username"
      :rules="rules.username"
      placeholder="用户名/手机号码"
      msg="手机号输入不合法"
    >
    </MyInput>
    <MyInput
      v-model="user.password"
      :rules="rules.password"
      placeholder="密码"
      msg="密码必须3-11位"
    >
    </MyInput>
    <MyInput
      v-model="user.nickname"
      :rules="rules.nickname"
      placeholder="昵称"
      msg="昵称必须2-8位的字符"
    >
    </MyInput>
    <div class="tips">
      已有账号？去 <router-link to="/login">登录</router-link>
    </div>
    <!-- 自定义按钮点击事件 -->
    <!-- 父组件传入type 可以改变样式 -->
    <MyButton @click="registerFn" type="primary">注册</MyButton>
  </div>
</template>

<script>
//自定义组件 引入 注册  应用
import MyButton from "../components/MyButton.vue";
//引入自定义输入框组件
import MyInput from "../components/MyInput.vue";
import { userRegisterAPI } from "../apis/user";
export default {
  components: {
    MyButton,
    MyInput,
  },
  data() {
    return {
      user: {
        username: "",
        password: "",
        nickname: "",
      },
      rules: {
        username: /^1\d{10}$/,
        password: /^[a-zA-Z0-9~!@#$%^&*()_+]{3,11}$/,
        nickname: /^.{2,8}$/,
      },
    };
  },
  methods: {
    async registerFn() {
      if (
        this.rules.username.test(this.user.username) &&
        this.rules.password.test(this.user.password) &&
        this.rules.nickname.test(this.user.nickname)
      ) {
        let res = await userRegisterAPI(this.user);
        // console.log(res);
        //解构出提示信息
        const { message } = res.data;
        if (message === "注册成功") {
          //延时跳转 - 延时器的写法
          //   this.$toast.success("注册成功");
          //   setTimeout(() => {
          //     this.$router.push({ path: "/login" });
          //   }, 2000);
          //延时跳转 - vant自带写法
          this.$toast({
            type: "success",
            // 支持通过\n换行
            message: "注册成功\n欢迎入坑",
            // 关闭时的回调函数
            onClose: () => {
              this.$router.push({ path: "/login" });
            },
          });
        } else {
          this.$toast.fail("注册失败\n" + message);
        }
        return;
      }
      this.$toast("输入的用户名/手机号码或密码或昵称不合法");
    },
  },
};
</script>

<style lang="less" scoped>
.close-btn {
  position: fixed;
  left: 20px;
  top: 20px;
  .iconfont {
    font-size: 20px;
    color: #666;
  }
}
.logo {
  display: flex;
  justify-content: center;
  padding: 80px, 0, 20px;
  .iconfont {
    color: #d81e06;
    font-size: 120px;
  }
}
.tips {
  padding: 0 50px;
  text-align: right;
}
</style>